
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
export default function request(params = {}) {
  return new Promise((resolve, reject) => {
      // {
      //   options:{
      //     loading:true,
      //     loadingText:'加载中'
      //   }
      // }
      //为请求添加loading 默认开启
      if (params.options && params.options.loading) {
          wx.showLoading({
              title: params.options.loadingText ? params.options.loadingText : '加载中',//加载提示
              mask: params.options.mask? true: false
          });
      }

      //设置请求header
      if (params.header) {
          //设置content-type
          params.header["content-type"] = params.header["content-type"] || "application/json";
      } else {
          //新增header
          params.header = {};
          //设置content-type
          params.header["content-type"] = "application/json";
      }
      //统一添加token
      let token = wx.getStorageSync('token');//从缓存同步获取token
      if (token) {
          params.header.token = token;
      }
      //发送请求
      wx.request({
          url:'http://localhost:8888'+ params.url,
          method: 'GET',
          data: '1',
          header: JSON,
          success: (res) => {//请求成功
              resolve(res.data);
          },
          fail: (err) => {//请求失败
              reject(err);
          },
          complete: (res) => {//关闭loading
              if (params.options && params.options.loading) {
                  wx.hideLoading();
              }
          }
      });

  });
};

module.exports = {
  formatTime,
  formatNumber,
}
